/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
 * MA  02110-1301, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */
package com.aionemu.gameserver.ai;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.apache.log4j.Logger;

import com.aionemu.gameserver.model.gameobjects.Creature;

import javolution.util.FastMap;

/**
 * @author Mr. Poke
 *
 */
public class AIClasss
{
	private static final Logger	log	= Logger.getLogger(AIClasss.class);

	private FastMap<String, Class<? extends AbstractAI>> classs = new FastMap<String, Class<? extends AbstractAI>>();
	
	public static final AIClasss getInstance()
	{
		return SingletonHolder.instance;
	}
	
	public Class<? extends AbstractAI> addClass (String name, Class<? extends AbstractAI> clazz)
	{
		return classs.put(name, clazz);
	}
	
	public AbstractAI getAIByName(String name, Creature creature)
	{
		Class<?> clazz = classs.get(name);
		if (clazz == null)
		{
			log.warn("Missing AI class: "+name);
			return new CreatureAI(creature);
		}

		try
		{
			Object[] parameters =
			{ creature };
			Constructor<?> constructor;
			constructor = clazz.getConstructor(Creature.class);
			AbstractAI ai = (AbstractAI) constructor.newInstance(parameters);
			return ai;
		}
		catch (InvocationTargetException e)
		{
			log.error(e.getTargetException());
		}
		catch (IllegalArgumentException e)
		{
			log.error(e);
		}
		catch (InstantiationException e)
		{
			log.error(e);
		}
		catch (IllegalAccessException e)
		{
			log.error(e);
		}
		catch (SecurityException e)
		{
			log.error(e);
		}
		catch (NoSuchMethodException e)
		{
			log.error(e);
		}
		return new CreatureAI(creature);
	}

	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder
	{
		protected static final AIClasss	instance	= new AIClasss();
	}
}
